package com.fishcoco.app.yunhang.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.view.View;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.fishcoco.app.yunhang.R;
import com.fishcoco.app.yunhang.entity.UniverResponseBody;
import com.fishcoco.app.yunhang.entity.YHRequestBody;
import com.fishcoco.app.yunhang.fragments.base.BaseMainFragment;
import com.fishcoco.app.yunhang.utils.constant.ConstantUtil;
import com.fishcoco.app.yunhang.utils.encryp.SymmetricEncoder3;
import com.fishcoco.app.yunhang.utils.gsonnull.NullStringToEmptyAdapterFactory;
import com.fishcoco.app.yunhang.utils.retrofit.RetrofitClient;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.fishcoco.app.yunhang.utils.constant.ConstantUtil.SP_KEY_APPNAME;
import static com.fishcoco.app.yunhang.utils.constant.ConstantUtil.SP_KEY_ID;
import static com.fishcoco.app.yunhang.utils.constant.ConstantUtil.SP_KEY_TOKEN;

public class Fragment3 extends BaseMainFragment {
    private TextInputEditText newUserNameET;
    private TextInputLayout newUserNameETIL;

    public static Fragment3 newInstance() {
        return new Fragment3();
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.fragment_three;
    }

    @Override
    protected void setUpView() {
        newUserNameET = $(R.id.et_new_username);
        newUserNameETIL = $(R.id.et_new_username_til);

        initClickListener(R.id.bt_new_username);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId())
        {
            case R.id.bt_new_username:
                attemptNewUserName();
                break;
        }
    }

    private void attemptNewUserName()
    {
        String oldUsername = SPUtils.getInstance(ConstantUtil.SP_KEY_APPNAME).getString(ConstantUtil.SP_KEY_USERNAME);
        String newUsername = newUserNameET.getText().toString().trim();
        if (!StringUtils.isTrimEmpty(newUsername))
        {
            newUserNameETIL.setErrorEnabled(false);
            if (!newUsername.equals(oldUsername))
            {
                newUserNameETIL.setErrorEnabled(false);
                newUsername(newUsername);
            } else {
                newUserNameETIL.setError("和当前用户名重复");
            }
        } else {
            newUserNameETIL.setError("请输入用户名");
        }
    }

    private void newUsername(String newUsername)
    {

        String id = SPUtils.getInstance(SP_KEY_APPNAME).getString(SP_KEY_ID);
        String token = SPUtils.getInstance(SP_KEY_APPNAME).getString(SP_KEY_TOKEN);

        JSONObject jo = new JSONObject();
        try {
            jo.put("id",id);
            jo.put("userName",newUsername);
            jo.put("token",token);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String encodeResult1 = SymmetricEncoder3.AESEncode(null,jo.toString());

        YHRequestBody body = new YHRequestBody();
        body.setRequestData(encodeResult1);
        String route = new Gson().toJson(body);
        RequestBody requestBody= RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),route);
        RetrofitClient.getInstance(getMContext()).createServiceReturnString()
                .changeUsername(requestBody)
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {

                        if (response.body()!=null) {
                            String result = SymmetricEncoder3.AESDncode(null, response.body());
                            LogUtils.d("result:" + result);
                            Gson gs = new  Gson();
                            Map<String,Object> map = gs.fromJson(result, Map.class);
                            Number resultCode = (Number)map.get("result");
                            LogUtils.d("resultCode:" + resultCode.intValue());
                            if (resultCode.intValue()==1)
                            {
                                LogUtils.d("resultMsg:" + map.get("msg"));
                                toast(""+map.get("msg"));
                            } else {
                                Gson gson  = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
                                UniverResponseBody responseBody = gson.fromJson(result,UniverResponseBody.class);
                                LogUtils.d("responseBody:" + responseBody.toString());
                                toast(responseBody.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        LogUtils.d("error:"+t.toString());
                    }
                });
    }
}
